<script setup lang="ts">
/**
 * @see {@link https://vuejs.org/api/sfc-script-setup.html#defineoptions}
 */
defineOptions({
  name: "Robot",
  inheritAttrs: false,
});

import dayjs from "dayjs";
import { RobotStatusList, updateRobot, FormRobot } from "@/api/robot";
import { onMounted, ref, watch } from "vue";
import { ElMessage } from "element-plus";

const loading = ref(false);

const total = ref(0);

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
});
const RobotStatusListT = ref([{}] as any);

/**
 * 查询
 */
function getRobotStatusList() {
  loading.value = true;
  RobotStatusList(queryParams.value)
    .then((res: any) => {
      if (res.code == 200) {
        const updatedRobotStatusList = res.data.records.map((record: any) => {
          const timestamp = record.createTime; // 假设时间戳单位为秒
          const date = dayjs(timestamp);
          const formattedDate = date.format("YYYY/MM/DD HH:mm:ss"); // 使用 dayjs.format 方法转换为指定的日期时间格式

          record.createTime = formattedDate;

          return record;
        });
        RobotStatusListT.value = updatedRobotStatusList;
        total.value = res.data.total;
        // console.log(RobotStatusListT.value, "res.data");
      }
    })
    .finally(() => {
      loading.value = false;
    });
}

onMounted(() => {
  getRobotStatusList(); // 初始化用户列表数据
});
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val;
  queryParams.value.pageNum = 1;

  getRobotStatusList();
};
const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val;
  getRobotStatusList();
  window.scrollTo({ top: 0, behavior: "smooth" }); // 立即回到顶部，并使用平滑滚动效果
};
const getStatus = (status: number) => {
  const STATUSES = [
    { id: -1, name: "离线" },
    { id: 0, name: "在线" },
    { id: 1, name: "工作中" },
    { id: 2, name: "充电中" },
    { id: 255, name: "故障" },
  ];
  const matched = STATUSES.find((item) => item.id === status);
  return matched ? matched.name : "";
};
// 枚举类型，定义状态码和对应的类型
enum RobotStatusType {
  SUCCESS = "success",
  WARNING = "warning",
  DANGER = "danger",
}

// 函数，根据状态码返回el-tag的类型
const statusType: (status: number) => string = (status) => {
  switch (status) {
    case 0:
      return RobotStatusType.SUCCESS;
    case -1:
      return RobotStatusType.WARNING;
    case 255:
      return RobotStatusType.DANGER;
    default:
      return "success"; // 默认类型
  }
};
const indexMethod = (index: any) => {
  // 1、index:代表当前行数据的下标
  // 2、下标+1:  分页不要纠结：这块不是业务，完全是数学问题！
  return (
    index + 1 + (queryParams.value.pageNum - 1) * queryParams.value.pageSize
  );
};
// --------------------
const mapInfo = ref();
const useMarker = () => {
  const markers = ref();

  function moveMarker(id: number, newX: number, newY: number) {
    const marker = markers.value.find((m) => m.id === id);
    if (marker) {
      const containerRect = document
        .querySelector(".marker-container")
        .getBoundingClientRect();
      const markerSize = 20; // Assuming marker size as 20px, adjust if necessary
      const maxX = containerRect.width - markerSize;
      const maxY = containerRect.height - markerSize;

      marker.x = Math.max(0, Math.min(newX, maxX));
      marker.y = Math.max(0, Math.min(newY, maxY));
      // 发送更新后的点位数据给后端
      mapInfo.value = markers.value.map((m) => ({
        id: m.id,
        x: m.x,
        y: m.y,
      }));
    }
  }

  return {
    markers,
    moveMarker,
  };
};
const { markers, moveMarker } = useMarker();
// -----------------------------------------------------------------------------
const dialogVisible = ref(false);
const bgdimg = ref();
const PositionID = ref();
const currentLocation = ref(); //当前坐标亮点
const trueLO = ref(false);
const Position = async (row: any) => {
  trueLO.value = false;
  markers.value = [];
  bgdimg.value = "";
  dialogVisible.value = true;
  PositionID.value = row.id;
  const res = await FormRobot(row.id);

  // setInterval(async () => {
  //   const res = await FormRobot(PositionID.value);
  //   currentLocation.value = res.data.currentLocation;
  // }, 10000);
  if (res.code == 200) {
    markers.value = JSON.parse(res.data.mapInfo);
    bgdimg.value = res.data.mapUrl;
    currentLocation.value = res.data.currentLocation;
    //currentLocation.value = res.data.currentLocation; //.replace(/^0+/, "")

    // 监听 res.data.currentLocation 的变化并更新 currentLocation.value
    // watch(
    //   () => res.data.currentLocation,
    //   (newVal) => {
    //     currentLocation.value = newVal;
    //     console.log("currentLocation updated:", currentLocation.value);
    //   },
    //   { immediate: true }
    // );

    console
      .log
      // res.data.currentLocation,
      // markers.value,
      // "位置弹框",
      //currentLocation.value
      ();
  }
};

const Close = () => {
  dialogVisible.value = false;
};

function startDrag(id: number, event: { clientX: any; clientY: any }) {
  const marker = markers.value.find((m) => m.id === id);
  if (!marker) return;

  const startX = event.clientX;
  const startY = event.clientY;
  const initialX = marker.x;
  const initialY = marker.y;

  function move(event: { clientX: number; clientY: number }) {
    const deltaX = event.clientX - startX;
    const deltaY = event.clientY - startY;
    moveMarker(id, initialX + deltaX, initialY + deltaY);
  }

  function stop() {
    window.removeEventListener("mousemove", move);
    window.removeEventListener("mouseup", stop);
  }

  window.addEventListener("mousemove", move);
  window.addEventListener("mouseup", stop);
}
const handleSubmit = () => {
  updateRobot({ id: PositionID.value, mapInfo: mapInfo.value })
    .then(() => {
      ElMessage.success("保存成功");
      // console.log("点位保存成功");
      Close();
    })
    .catch((error) => {
      console.error("保存点位时出错:", error);
    });
};
const newMarker = {
  id: 1,
  x: 0,
  y: 0,
};
const addNewMarker = () => {
  // 假设这里给新点分配一个唯一的 ID
  newMarker.id = markers.value.length + 1;
  markers.value.push({ ...newMarker });
};

// function handleDelete(id) {
//   const index = markers.value.findIndex((m) => m.id === id);
//   if (index !== -1) {
//     markers.value.splice(index, 1); // 从 markers 数组中删除对应的 marker
//     // 在这里可以添加删除后的其他逻辑，比如保存更新等
//     updateRobot({ id: PositionID.value, mapInfo: markers.value })
//       .then(() => {
//         ElMessage.success("删除成功");
//         console.log("点位删除成功");
//       })
//       .catch((error) => {
//         console.error("删除点位时出错:", error);
//       });
//   }
// }
function handleModify(id) {
  const markerIndex = markers.value.findIndex((m) => m.id === id);
  if (markerIndex !== -1) {
    const marker = markers.value[markerIndex];
    const action = prompt("请选择操作:\n1. 编辑\n2. 删除");

    if (action === "1") {
      // 编辑操作
      const newName = prompt("修改位置坐标:", marker.id);
      if (newName !== null) {
        marker.id = newName;
        mapInfo.value = markers.value;
        // updateRobot({ id: PositionID.value, mapInfo: markers.value })
        //   .then(() => {
        //     ElMessage.success("修改成功");
        //     console.log("点位修改成功");
        //   })
        //   .catch((error) => {
        //     console.error("修改点位时出错:", error);
        //   });
      }
    } else if (action === "2") {
      // 删除操作
      markers.value.splice(markerIndex, 1);
      mapInfo.value = markers.value;
      // updateRobot({ id: PositionID.value, mapInfo: markers.value })
      //   .then(() => {
      //     ElMessage.success("删除成功");
      //     console.log("点位删除成功");
      //   })
      //   .catch((error) => {
      //     console.error("删除点位时出错:", error);
      //     // 如果删除失败，可能需要将 marker 重新插入到 markers 中
      //     markers.value.splice(markerIndex, 0, marker);
      //   });
    } else {
      // 用户取消操作或输入无效选项
    }
  }
}
</script>

<template>
  <div class="app-container">
    <el-row>
      <el-col>
        <el-card shadow="never">
          <el-table v-loading="loading" :data="RobotStatusListT" :border="true">
            <el-table-column
              type="index"
              width="80"
              label="序号"
              :align="'center'"
              :index="indexMethod"
            />
            <el-table-column
              label="机器人名称"
              align="center"
              prop="robotName"
            />
            <el-table-column
              label="机器人编号"
              align="center"
              prop="robotCode"
            />
            <el-table-column
              label="机器人状态"
              prop="agvStatus"
              :align="'center'"
            >
              <template #default="{ row }">
                <el-tag :type="statusType(row.robotStatus)">
                  {{ getStatus(row.robotStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="电量" align="center" prop="currentPower" />
            <el-table-column label="主板" align="center" prop="mainBoard" />
            <el-table-column label="MAC地址" align="center" prop="mac" />
            <el-table-column label="机器人类型" align="center" prop="type" />

            <el-table-column
              label="自检报告"
              align="center"
              prop="selfInspectionReport"
              show-overflow-tooltip
            />

            <el-table-column
              label="创建时间"
              align="center"
              prop="createTime"
            />
            <el-table-column fixed="right" label="操作" align="center">
              <template #default="{ row }">
                <el-button
                  v-if="row.mapUrl"
                  type="primary"
                  link
                  style="font-size: 20px"
                  size="small"
                  @click="Position(row)"
                  icon="Location"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            style="margin-top: 15px"
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 30, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-card>
      </el-col>
    </el-row>

    <el-dialog
      v-model="dialogVisible"
      :before-close="Close"
      style="background-color: transparent; width: 680px"
    >
      <div
        class="marker-container"
        :style="{ backgroundImage: 'url(' + bgdimg + ')' }"
      >
        <div
          v-for="marker in markers"
          :key="marker.id"
          class="marker"
          :style="{
            left: marker.x + 'px',
            top: marker.y + 'px',
            backgroundColor: marker.id == currentLocation ? 'green' : '',
          }"
          @mousedown="startDrag(marker.id, $event)"
          @dblclick="handleModify(marker.id)"
        >
          <span
            style="
              display: flex;
              font-size: 10px;
              justify-content: center;
              align-items: center;
            "
            >{{ marker.id }}</span
          >
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="addNewMarker">新增点位</el-button>
          <el-button type="primary" @click="handleSubmit">保 存</el-button>
          <el-button @click="Close">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
.marker-container {
  position: relative;
  width: 650px;
  height: 650px;
  background-color: transparent;
  background-size: 650px 650px; /* 设置宽度为100像素，高度为50像素 */
}

.marker {
  position: absolute;
  width: 15px;
  height: 15px;
  background-color: red; /* Adjust marker style */
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: bottom;
  color: white;
  font-weight: bold;
}
</style>
